﻿// Define a blackberry viewport
Ext.define('Ext.viewport.Blackberry', {
    extend: 'Ext.viewport.Default',
    constructor: function(config) {
        // Blackberry does not like height: 100%   
        this.superclass.config.height = this.getWindowHeight() + 'px';
        this.callParent([config]);
        return this;
    },
    getWindowHeight: function() {
        if (Ext.os.version.lt('7.0')) {
            return window.innerHeight;
        }
        else {
            return window.innerHeight + 42;
        }
    }

}, function() {

});


// Insert a new Blackberry specific viewport
Ext.override(Ext.viewport.Viewport,
{
    constructor: function(config) {
        var osName = Ext.os.name,
            viewportName, viewport;
        switch (osName) {
            case 'Android':
                viewportName = 'Android';
                break;
            case 'BlackBerry':
                viewportName = 'Blackberry';
                break;
            case 'iOS':
                viewportName = 'Ios';
                break;
            default:
                viewportName = 'Default';
        }
        viewport = Ext.create('Ext.viewport.' + viewportName, config);
        return viewport;
    }
});

Ext.application({
    name: 'LibOC',

    launch: function() {
        //window.localStorage.clear();

        Ext.regModel('ordenCompraModel',
        {
            idProperty: 'id',
            fields: [
                { name: 'id', type: 'string' },
                { name: 'PO', type: 'string' },
                { name: 'Sociedad', type: 'string' },
                { name: 'OrgCompras', type: 'string' },
                { name: 'CondPago', type: 'string' },
                { name: 'CondPagoT', type: 'string' },
                { name: 'ClaseDoc', type: 'string' },
                { name: 'ClaseDocT', type: 'string' },
                { name: 'GrpCompras', type: 'string' },
                { name: 'Moneda', type: 'string' },
                { name: 'TipoCambio', type: 'float' },
                { name: 'CodProveedor', type: 'string' },
                { name: 'DescProveedor', type: 'string' },
                { name: 'Fecha', type: 'string' },
                { name: 'TotNeto', type: 'float' },
                { name: 'TotBruto', type: 'float' },
                { name: 'LibGrp', type: 'string' },
                { name: 'LibEst', type: 'string' },
                { name: 'LibInd', type: 'string' },
                { name: 'LibCod', type: 'string' },
                { name: 'NomSoc', type: 'string' },
                { name: 'NomCrea', type: 'string' },
                { name: 'Telefono', type: 'string' },
                { name: 'CodUsuario', type: 'string' },
                { name: 'NomSolicitante', type: 'string' },
                { name: 'DesUsuario', type: 'string' },
                { name: 'Items', type: 'array' },
                { name: 'Contactos', type: 'array' },
                { name: 'Solicitantes', type: 'array' },
                { name: 'Texto', type: 'string' }
            ]
        });

        Ext.regModel('itemModel',
        {
            fields: [
                { name: 'PO', type: 'string' },
                { name: 'Pos', type: 'string' },
                { name: 'NroOrd', type: 'string' },
                { name: 'ActFijo', type: 'string' },
                { name: 'CentCO', type: 'string' },
                { name: 'NombRespCO', type: 'string' },
                { name: 'Solicitante', type: 'string' },
                { name: 'Cod', type: 'string' },
                { name: 'Desc', type: 'string' },
                { name: 'UM', type: 'string' },
                { name: 'Cant', type: 'float' },
                { name: 'Precio', type: 'float' },
                { name: 'Total', type: 'float' },
                { name: 'Moneda', type: 'string' },
                { name: 'DescCentCO', type: 'string' },
                { name: 'DescNroOrd', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'itemStore'
            }
        });

        Ext.regModel('contactoModel',
        {
            fields: [
                { name: 'LIFNR', type: 'string' },
                { name: 'NAME_TEXT', type: 'string' },
                { name: 'TEL_NUMBER', type: 'string' },
                { name: 'TEL_EXTENS', type: 'string' },
                { name: 'MOB_NUMBER', type: 'string' },
                { name: 'SMTP_ADDR', type: 'string' },
                { name: 'DEPARTMENT', type: 'string' },
                { name: 'FUNCTION', type: 'string' },
                { name: 'BNAME', type: 'string' },
                { name: 'STREET', type: 'string' },
                { name: 'POST_CODE1', type: 'string' },
                { name: 'CITY1', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'contactoStore'
            }
        });

        Ext.regModel('accesoModel',
        {
            fields: [
                { name: 'servidor', type: 'string' },
                { name: 'nombre', type: 'string' },
                { name: 'puerto', type: 'string' },
                { name: 'protocolo', type: 'string' },
                { name: 'hostValue', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'accesoStore'
            }
        });

        Ext.regModel('solicitanteModel',
        {
            fields: [
                { name: 'LIFNR', type: 'string' },
                { name: 'NAME_TEXT', type: 'string' },
                { name: 'TEL_NUMBER', type: 'string' },
                { name: 'TEL_EXTENS', type: 'string' },
                { name: 'MOB_NUMBER', type: 'string' },
                { name: 'SMTP_ADDR', type: 'string' },
                { name: 'DEPARTMENT', type: 'string' },
                { name: 'FUNCTION', type: 'string' },
                { name: 'BNAME', type: 'string' },
                { name: 'STREET', type: 'string' },
                { name: 'POST_CODE1', type: 'string' },
                { name: 'CITY1', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'solicitanteStore'
            }
        });

        Ext.regModel('statusModel',
        {
            fields: [
                { name: 'valor', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'statusStore'
            }
        });

        Ext.regModel('SAPUserBE',
        {
            fields: [
                { name: 'Id', type: 'string' },
                { name: 'Uname', type: 'string' },
                { name: 'Passwd', type: 'string' },
                { name: 'Mandt', type: 'string' },
                { name: 'Server', type: 'string' },
                { name: 'SapRouter', type: 'string' },
                { name: 'Langu', type: 'string' },
                { name: 'Instance', type: 'string' },
                { name: 'SysId', type: 'string' }
            ],

            validations: [
                { type: 'presence', field: 'Uname', message: 'Debe ingresar nombre de usuario' },
                { type: 'presence', field: 'Passwd', message: 'Debe ingresar clave de acceso' },
                { type: 'presence', field: 'Langu', message: 'Debe seleccionar el idioma' }
            ]
        });

        Ext.regStore('ordenCompraStore',
        {
            //autoLoad: true,
            model: 'ordenCompraModel',
            proxy: {
                type: 'localstorage',
                id: 'ordenCompraStore'
            },
            listeners: {
                'beforeload': function(ele) {
                    var sto = Ext.getStore('statusStore');
                    if (sto.last()) {
                        ele.setProxy({
                            id: 'ordenCompraStore',
                            type: 'rest',
                            url: 'resources/txt/data.txt',
                            reader: {
                                type: 'json',
                                rootProperty: 'lstItemsResale'
                            }
                        });
                    }
                }
            }
        });

        Ext.regStore('itemStore',
        {
            autoLoad: true,
            model: 'itemModel'
        });

        Ext.regStore('statusStore',
        {
            autoLoad: true,
            model: 'statusModel'
        });

        Ext.regStore('contactoStore',
        {
            autoLoad: true,
            model: 'contactoModel'
        });

        Ext.regStore('solicitanteStore',
        {
            autoLoad: true,
            model: 'solicitanteModel'
        });

        Ext.regStore('accesoStore',
        {
            autoLoad: true,
            model: 'accesoModel'
        });

        Ext.regStore('SAPUserStore',
        {
            proxy: new Ext.data.LocalStorageProxy(
	        {
	            id: 'SAPUserStore',
	            proxy:
		        {
		            idProperty: 'SAPUserStore'
		        }
	        }),
            model: 'SAPUserBE',
            autoLoad: true,
            autoSave: true
        });

        var solicitanteOC = new Ext.form.FormPanel({
            id: 'solicitanteOC',
            items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                title: 'Creado por',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function() {
                        panelPrincipal.animateActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
                }]
            },
            {
                xtype: 'panel',
                layout: 'hbox',
                items: [
                {
                    xtype: 'panel',
                    flex: 1,
                    styleHtmlContent: true,
                    html: [
                        '<div align="center"><img src="resources/img/contact.png" width="48" heigth="48"/></div>'
                    ]
                },
                {
                    xtype: 'dataview',
                    store: 'solicitanteStore',
                    flex: 1,
                    styleHtmlContent: true,
                    itemTpl: [
                        '<div class="textoContacto">{NAME_TEXT}<br />' +
                        '{FUNCTION}<br />' +
                        '{DEPARTMENT}</div>',
                    ]
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Información del Creador',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'urlfield',
                    label: 'Teléfono',
                    readOnly: true,
                    name: 'TEL_NUMBER',
                    listeners: {
                        'focus': function(ele) {
                            var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                            var nro = solicitanteOC.getRecord().data.TEL_NUMBER;
                            if (nro) {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                                    if (res == 'si') {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Extensión',
                    name: 'TEL_EXTENS',
                    readOnly: true
                },
                {
                    xtype: 'urlfield',
                    label: 'Móvil',
                    name: 'MOB_NUMBER',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele) {
                            var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                            var nro = solicitanteOC.getRecord().data.MOB_NUMBER;
                            if (nro) {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                                    if (res == 'si') {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'urlfield',
                    label: 'Correo',
                    name: 'SMTP_ADDR',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele) {
                            var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                            var nro = solicitanteOC.getRecord().data.SMTP_ADDR;
                            if (nro) {
                                Ext.Msg.confirm('Contacto', 'Enviar correo a ' + nombre + "?", function(res) {
                                    if (res == 'si') {
                                        window.location = 'mailto:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                }
                ]
            },
            {
                xtype: 'fieldset',
                title: 'Compañia',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'textareafield',
                    label: 'Dirección',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = solicitanteOC.getRecord();
                            ele.setValue(record.data.STREET + '\n' + record.data.CITY1 + '\n' + record.data.POST_CODE1);
                        }
                    }
                }]
            }]
        });

        var contactoOC = new Ext.form.FormPanel({
            id: 'contactoOC',
            items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                title: 'Proveedor',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function() {
                        panelPrincipal.animateActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
                }]
            },
            {
                xtype: 'panel',
                layout: 'hbox',
                items: [
                {
                    xtype: 'panel',
                    flex: 1,
                    styleHtmlContent: true,
                    html: [
                        '<div align="center"><img src="resources/img/contact.png" width="48" heigth="48"/></div>'
                    ]
                },
                {
                    xtype: 'dataview',
                    cls: 'twitterView',
                    store: 'contactoStore',
                    flex: 1,
                    styleHtmlContent: true,
                    itemTpl: [
                        '<div class="textoContacto">{NAME_TEXT}<br />' +
                        '{FUNCTION}<br />' +
                        '{DEPARTMENT}</div>',
                   ]
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Información del Proveedor',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'urlfield',
                    label: 'Teléfono',
                    name: 'TEL_NUMBER',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele) {
                            var nombre = contactoOC.getRecord().data.NAME_TEXT;
                            var nro = contactoOC.getRecord().data.TEL_NUMBER;
                            if (nro) {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                                    if (res == 'si') {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Extensión',
                    name: 'TEL_EXTENS',
                    readOnly: true
                },
                {
                    xtype: 'urlfield',
                    label: 'Móvil',
                    name: 'MOB_NUMBER',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele) {
                            var nombre = contactoOC.getRecord().data.NAME_TEXT;
                            var nro = contactoOC.getRecord().data.MOB_NUMBER;
                            if (nro) {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                                    if (res == 'si') {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'urlfield',
                    label: 'Correo',
                    name: 'SMTP_ADDR',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele) {
                            var nombre = contactoOC.getRecord().data.NAME_TEXT;
                            var nro = contactoOC.getRecord().data.SMTP_ADDR;
                            if (nro) {
                                Ext.Msg.confirm('Contacto', 'Enviar correo a ' + nombre + "?", function(res) {
                                    if (res == 'si') {
                                        window.location = 'mailto:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Compañia',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'textareafield',
                    label: 'Dirección',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = contactoOC.getRecord();
                            ele.setValue(record.data.STREET + '\n' + record.data.CITY1 + '\n' + record.data.POST_CODE1);
                        }
                    }
                }]
            }]
        });

        var itemOC = new Ext.form.FormPanel({
            id: 'itemOC',
            items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                title: 'Posición',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function() {
                        panelPrincipal.animateActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Datos de Posición',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nro. de Pos.',
                    name: 'Pos',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Cantidad',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.Cant + ' ' + record.data.UM);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Precio Unit.',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.Precio + ' ' + record.data.Moneda);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'CeCo',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.CentCO + ' - ' + record.data.DescCentCO);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Responsable CO',
                    name: 'NombRespCO',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Orden',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.NroOrd + ' - ' + record.data.DescNroOrd);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Activo Fijo',
                    name: 'ActFijo',
                    readOnly: true
                }]
            }]
        });

        var form = new Ext.form.FormPanel({
            id: 'form',
            scrollable: false,
            items: [
            {
                xtype: 'fieldset',
                items: [
                {
                    xtype: 'button',
                    text: 'Liberar',
                    ui: 'action',
                    handler: function() {
                        var sto = Ext.getStore('statusStore');
                        if (sto.last()) {
                            var PO = detalleOC.getRecord().data.PO;
                            Ext.Msg.alert('Aviso', 'El pedido ' + PO + ' ha sido liberado');
                            panelFloat.hide();
                            var sto = listaOC.getStore().data.items;
                            for (var i = 0; i < sto.length; i++) {
                                var currentPO = sto[i];
                                if (currentPO.data.PO == PO) {
                                    listaOC.getStore().remove(currentPO);
                                    listaOC.getStore().sync();
                                    listaOC.refresh();
                                    panelPrincipal.setActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                                }
                            }
                        }
                        else {
                            var SAPUserStore = Ext.getStore('SAPUserStore');
                            validateUser(SAPUserStore); //validar login de usuario
                            //---------------------------------------------------
                            if (navigator.onLine) {
                                Ext.Viewport.setMasked({
                                    xtype: 'loadmask',
                                    message: 'Conectando ...'
                                });
                                var LibCod = detalleOC.getRecord().data.LibCod;
                                var PO = detalleOC.getRecord().data.PO;
                                var sto = Ext.getStore('accesoStore');
                                var host = sto.last().data.hostValue;
                                form.add({ xtype: 'hiddenfield', id: 'LibCod', name: 'LibCod', value: LibCod });
                                form.add({ xtype: 'hiddenfield', id: 'PO', name: 'PO', value: PO });
                                var SAPUserStore = Ext.getStore('SAPUserStore');
                                prepareForm(form, SAPUserStore);
                                form.submit({
                                    method: 'POST',
                                    url: host + '/release.aspx',
                                    success: function(form, action) {
                                        Ext.Viewport.setMasked(false);
                                        if (action.success) {
                                            var mensaje = action.errors.reason;
                                            panelFloat.hide();
                                            form.submit({
                                                method: 'POST',
                                                url: host + '/List.aspx',
                                                success: function(form, action) {
                                                    Ext.Viewport.setMasked(false);
                                                    if (action.success) {
                                                        listaOC.getStore().getProxy().clear();
                                                        listaOC.getStore().data.clear();
                                                        listaOC.getStore().sync();
                                                        listaOC.refresh();
                                                        listaOC.getStore().add(action.lstItemsResale);
                                                        listaOC.getStore().sync();
                                                        var now = new Date();
                                                        var dia = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
                                                        var mes = (now.getMonth() + 1) < 10 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
                                                        var minutos = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
                                                        listaOCPanel.items.items[2].setTitle('Actualizado  al ' + dia + '.' + mes + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + minutos);
                                                        Ext.Msg.alert('Aviso', mensaje);
                                                        panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                                                    }
                                                    else {
                                                        Ext.Msg.alert('Error', action.errors.reason);
                                                    }
                                                },
                                                failure: function(form, action) {
                                                    Ext.Viewport.setMasked(false);
                                                    //Falta manejo de error por timeout
                                                    if (action.errors) {
                                                        Ext.Msg.alert('Error', action.errors.reason);
                                                    }
                                                    else {
                                                        Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                                                    }
                                                }
                                            });
                                        }
                                        else {
                                            Ext.Msg.alert('Error', action.errors.reason);
                                        }
                                    },
                                    failure: function(form, action) {
                                        Ext.Viewport.setMasked(false);
                                        if (action.errors) {
                                            Ext.Msg.alert('Error', action.errors.reason);
                                        }
                                        else {
                                            Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                                        }
                                    }
                                });
                            }
                            else {
                                Ext.Msg.alert('Error', 'Verifique la conexión a internet');
                            }
                        }
                    }
                },
                {
                    xtype: 'button',
                    text: 'Cancelar',
                    ui: 'normal',
                    handler: function() {
                        panelFloat.hide();
                    }
                }]
            }]
        });

        var panelFloat = new Ext.Panel({
            id: 'panelFloat',
            layout: 'fit',
            centered: true,
            modal: true,
            hidden: true,
            hideOnMaskTap: true,
            width: 200,
            height: 70,
            items: [form]
        });

        var detalleOC = new Ext.form.FormPanel({
            id: 'detalleOC',
            scrollable: 'vertical',
            items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                title: 'Detalle',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function() {
                        panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Datos',
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nro. Doc.',
                    name: 'PO',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Tipo Doc.',
                    name: 'ClaseDocT',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Sociedad',
                    name: 'NomSoc',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Monto Total',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = detalleOC.getRecord();
                            ele.setValue(record.data.TotBruto + ' ' + record.data.Moneda);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Texto',
                    name: 'Texto',
                    readOnly: true
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Creado por',
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nombre',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = detalleOC.getRecord();
                            ele.setValue(record.data.NomSolicitante);
                        },
                        'focus': function(ele) {
                            var rec = detalleOC.getRecord().data.CodUsuario;
                            var sto = Ext.getStore('solicitanteStore');
                            var solicitante = sto.findRecord('BNAME', rec);
                            if (solicitante) {
                                solicitanteOC.reset();
                                solicitanteOC.setRecord(solicitante);
                                solicitanteOC.items.items[1].items.items[1].refresh();
                                panelPrincipal.animateActiveItem(solicitanteOC, { type: 'slide', direction: 'left' });
                            }
                        }
                    }
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Proveedor',
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nombre',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele) {
                            var record = detalleOC.getRecord();
                            ele.setValue(record.data.DescProveedor);
                        },
                        'focus': function(ele) {
                            console.log("prueba");
                            var rec = detalleOC.getRecord().data.CodProveedor;
                            var sto = Ext.getStore('contactoStore');
                            var contacto = sto.findRecord('LIFNR', rec);
                            if (contacto) {
                                contactoOC.reset();
                                contactoOC.setRecord(contacto);
                                contactoOC.items.items[1].items.items[1].refresh();
                                panelPrincipal.animateActiveItem(contactoOC, { type: 'slide', direction: 'left' });
                            }
                        }
                    }
                }]
            },
            {
                xtype: 'fieldset',
                title: 'Productos',
                items: [
                {
                    xtype: 'list',
                    store: 'itemStore',
                    scrollable: false,
                    allowDeselect: true,
                    itemTpl:
                    '<div class="getAutoHeight">' +
                    '<div class="doc-img"><img src="resources/img/item.png" width="20" height="20">' +
                    '</div>' +
                    '<div class="list-list">' +
                        '<div style="font-weight:bold">{Desc}</div>' +
                    '{Cant} {UM}&nbsp;x&nbsp;{Precio}&nbsp;{Moneda}' +
	                '<br />' +
	                '{Total}&nbsp;{Moneda}' +
	                '</div>' +
                    '<div class="doc-img2"><img src="resources/img/arrow.png" width="20" height="20">' +
                    '</div>',
                    listeners: {
                        itemtap: function(list, item, index, record) {
                            itemOC.reset();
                            itemOC.setRecord(record);
                            itemOC.items.items[0].setTitle('Posición ' + ltrim(record.data.Pos));
                            itemOC.items.items[1].setTitle(record.data.Desc);
                            panelPrincipal.animateActiveItem(itemOC, { type: 'slide', direction: 'left' });
                        }
                    }
                }]
            },
            {
                xtype: 'toolbar',
                id: 'tbLiberar',
                docked: 'bottom',
                items: [
                {
                    xtype: 'button',
                    text: 'Liberar',
                    id: 'btnLiberar',
                    ui: 'confirm',
                    handler: function() {
                        panelFloat.showBy(detalleOC.getComponent('tbLiberar').getComponent('btnLiberar'));
                    }
                },
                {
                    xtype: 'spacer'
                },
                {
                    xtype: 'button',
                    text: 'Cancelar',
                    ui: 'decline',
                    handler: function() {
                        panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                    }
                }]
            }]
        });

        var listaOC = new Ext.dataview.List({
            id: 'listaOC',
            store: 'ordenCompraStore',
            allowDeselect: true,
            deferEmptyText: false,
            emptyText: 'No hay Órdenes de Compras pendientes de liberación.',
            scrollable: {
                direction: 'vertical',
                directionLock: true
            },
            loadingText: "Cargando Órdenes...",
            itemTpl:
            '<div class="getAutoHeight">' +
            '<div class="doc-img"><img src="resources/img/shopping_cart.png" width="30" height="30">' +
            '</div>' +
            '<div class="list-doci">' +
                '<div style="font-weight:bold;">{DescProveedor}</div>' +
            '{PO}&nbsp;&nbsp;-&nbsp;&nbsp;{NomSolicitante}' +
            '</div>' +
            '<div class="list-docd">' +
                '<div style="font-weight:bold;">{TotBruto}&nbsp;&nbsp;{Moneda}</div>' +
            '{Fecha}' +
            '</div>' +
            '<div class="doc-img2"><img src="resources/img/arrow.png" width="20" height="20">' +
            '</div>',
            listeners: {
                painted: function(ele) {
                    ele.getStore().load();
                },
                itemtap: function(list, item, index, record) {
                    detalleOC.setRecord(record);
                    var PO = record.data.PO;
                    var sto = Ext.getStore('itemStore');
                    sto.getProxy().clear();
                    sto.data.clear();
                    sto.sync();
                    sto.add(record.data.Items);
                    sto.sync();
                    var sto = Ext.getStore('contactoStore');
                    sto.getProxy().clear();
                    sto.data.clear();
                    sto.sync();
                    sto.add(record.data.Contactos);
                    sto.sync();
                    var sto = Ext.getStore('solicitanteStore');
                    sto.getProxy().clear();
                    sto.data.clear();
                    sto.sync();
                    sto.add(record.data.Solicitantes);
                    sto.sync();
                    detalleOC.items.items[4].items.items[0].refresh();
                    detalleOC.items.items[0].setTitle('Ord. Compra');
                    panelPrincipal.animateActiveItem(detalleOC, { type: 'slide', direction: 'left' });
                }
            }
        });

        var listaOCPanel = new Ext.form.FormPanel({
            id: 'listaOCPanel',
            layout: 'fit',
            items: [
            {
                xtype: 'toolbar',
                title: 'Lista',
                docked: 'top',
                items: [
	            {
	                xtype: 'button',
	                ui: 'decline',
	                text: 'Salir',
	                handler: function() {
	                    var sto = Ext.getStore('accesoStore');
	                    if (sto.last()) {
	                        limpiar();
	                        loginForm.reset();
	                        panelPrincipal.animateActiveItem(loginForm, { type: 'slide', direction: 'right' });
	                    }
	                    else {
	                        panelPrincipal.animateActiveItem(introForm, { type: 'slide', direction: 'right' });
	                    }
	                }
	            },
	            {
	                xtype: 'spacer'
                }]
            },
            listaOC,
            {
                xtype: 'toolbar',
                docked: 'bottom',
                items: [
                {
                    xtype: 'button',
                    ui: 'confirm',
                    iconCls: 'refresh',
                    iconMask: true,
                    handler: function() {
                        var sto = Ext.getStore('statusStore');
                        if (sto.last()) {
                            listaOC.refresh();
                            var now = new Date();
                            var dia = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
                            var mes = (now.getMonth() + 1) < 10 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
                            var minutos = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
                            listaOCPanel.items.items[2].setTitle('Actualizado  al ' + dia + '.' + mes + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + minutos);
                        }
                        else {
                            var SAPUserStore = Ext.getStore('SAPUserStore');
                            validateUser(SAPUserStore); //validar login de usuario
                            //---------------------------------------------------
                            if (navigator.onLine) {
                                Ext.Viewport.setMasked({
                                    xtype: 'loadmask',
                                    message: 'Conectando ...'
                                });
                                var sto = Ext.getStore('accesoStore');
                                var host = sto.last().data.hostValue;
                                var SAPUserStore = Ext.getStore('SAPUserStore');
                                prepareForm(listaOCPanel, SAPUserStore);
                                listaOCPanel.submit({
                                    method: 'POST',
                                    url: host + '/List.aspx',
                                    success: function(form, action) {
                                        Ext.Viewport.setMasked(false);
                                        if (action.success) {
                                            listaOC.getStore().getProxy().clear();
                                            listaOC.getStore().data.clear();
                                            listaOC.getStore().sync();
                                            listaOC.refresh();
                                            listaOC.getStore().add(action.lstItemsResale);
                                            listaOC.getStore().sync();
                                            var now = new Date();
                                            var dia = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
                                            var mes = (now.getMonth() + 1) < 10 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
                                            var minutos = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
                                            listaOCPanel.items.items[2].setTitle('Actualizado  al ' + dia + '.' + mes + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + minutos);
                                        }
                                        else {
                                            Ext.Msg.alert('Error', action.errors.reason);
                                        }
                                    },
                                    failure: function(form, action) {
                                        Ext.Viewport.setMasked(false);
                                        //Falta manejo de error por timeout
                                        if (action.errors) {
                                            Ext.Msg.alert('Error', action.errors.reason);
                                        }
                                        else {
                                            Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                                        }
                                    }
                                });
                            }
                            else {
                                Ext.Msg.alert('Error', 'Verifique la conexión a internet');
                            }
                        }
                    }
                },
	            {
	                xtype: 'spacer'
	            },
                {
                    xtype: 'spacer'
                }]
            }]
        });

        var accesoForm = new Ext.form.FormPanel({
            id: 'accesoForm',
            scrollable: 'vertical',
            items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                title: 'Accesos'
            },
        	{
        	    xtype: 'toolbar',
        	    docked: 'bottom',
        	    items: [
        	    {
        	        xtype: 'button',
        	        text: 'Volver',
        	        ui: 'dark',
        	        handler: function() {
        	            var sto = Ext.getStore('accesoStore');
        	            if (sto.last()) {
        	                panelPrincipal.animateActiveItem(loginForm, { type: 'slide', direction: 'left' });
        	            }
        	            else {
        	                panelPrincipal.animateActiveItem(introForm, { type: 'slide', direction: 'left' });
        	            }
        	        }
        	    },
	            {
	                xtype: 'spacer'
	            },
	            {
	                xtype: 'button',
	                text: 'Grabar',
	                ui: 'confirm',
	                handler: function() {
	                    var ser = accesoForm.getValues().servidor;
	                    var nom = accesoForm.getValues().nombre;
	                    var pue = accesoForm.getValues().puerto;
	                    var pro = accesoForm.getValues().protocolo;
	                    if (ser == '' && nom == '' && pue == '' && pro == '') {
	                        var sto = Ext.getStore('accesoStore');
	                        sto.getProxy().clear();
	                        sto.data.clear();
	                        sto.sync();
	                        panelPrincipal.animateActiveItem(introForm, { type: 'slide', direction: 'right' });
	                    }
	                    else {
	                        accesoForm.reset();
	                        hostValue(ser, nom, pue, pro, panelPrincipal);
	                    }
	                }
                }]
        	},
        	{
        	    xtype: 'fieldset',
        	    title: 'Parámetros conexión al sistema',
        	    defaults: {
        	        labelWidth: '55%'
        	    },
        	    items: [
        		{
        		    xtype: 'textfield',
        		    label: 'Servidor de aplicación',
        		    name: 'servidor',
        		    listeners: {
        		        'painted': function(ele) {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec) {
        		                ele.setValue(rec.data.servidor);
        		            }
        		        }
        		    }
        		},
        		{
        		    xtype: 'textfield',
        		    label: 'Nombre de la aplicación',
        		    name: 'nombre',
        		    listeners: {
        		        'painted': function(ele) {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec) {
        		                ele.setValue(rec.data.nombre);
        		            }
        		        }
        		    }
        		},
        		{
        		    xtype: 'textfield',
        		    label: 'Puerto',
        		    name: 'puerto',
        		    listeners: {
        		        'painted': function(ele) {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec) {
        		                ele.setValue(rec.data.puerto);
        		            }
        		        }
        		    }
        		},
        		{
        		    xtype: 'textfield',
        		    label: 'Protocolo',
        		    name: 'protocolo',
        		    listeners: {
        		        'painted': function(ele) {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec) {
        		                ele.setValue(rec.data.protocolo);
        		            }
        		        }
        		    }
                }]
            }]
        });

        var loginForm = new Ext.form.FormPanel({
            id: 'loginForm',
            scrollable: 'vertical',
            items: [
            {
                xtype: 'fieldset',
                title: nombreEmpresa
            },
            {
                xtype: 'fieldset',
                items: [
	            {
	                xtype: 'textfield',
	                id: 'usuario',
	                name: 'usuario',
	                label: 'Usuario',
	                useClearIcon: true,
	                required: true,
	                placeHolder: 'Ingrese usuario'
	            },
	            {
	                xtype: 'passwordfield',
	                id: 'clave',
	                name: 'clave',
	                label: 'Clave',
	                useClearIcon: true,
	                required: true,
	                placeHolder: 'Ingrese clave'
                }]
            },
            {
                xtype: 'fieldset',
                hidden: true,
                items: [
	            {
	                xtype: 'selectfield',
	                id: 'idioma',
	                name: 'idioma',
	                label: 'Idioma',
	                options: [
		            {
		                text: 'Español',
		                value: 'ES'
                    }]
                }]
            },
            {
                xtype: 'toolbar',
                docked: 'bottom',
                items: [
	            {
	                xtype: 'button',
	                text: 'Accesos',
	                ui: 'dark',
	                handler: function() {
	                    panelPrincipal.animateActiveItem(accesoForm, { type: 'slide', direction: 'right' });
	                }
	            },
	            {
	                xtype: 'spacer'
	            },
	            {
	                xtype: 'button',
	                text: 'Entrar',
	                ui: 'confirm',
	                handler: function() {
	                    if (navigator.onLine) {
	                        var sto = Ext.getStore('accesoStore');
	                        var host = sto.last().data.hostValue;
	                        var loUser = Ext.ModelMgr.create({
	                            Uname: loginForm.getValues().usuario,
	                            Passwd: loginForm.getValues().clave,
	                            Langu: loginForm.getValues().idioma
	                        }, 'SAPUserBE');
	                        var errors = loUser.validate();
	                        var message = "";
	                        if (!errors.isValid()) {
	                            errors.each(function(item, index, length) {
	                                message += item.getMessage() + "<br>";
	                            });
	                            Ext.Msg.alert("Error", message, function() { });
	                            return false;
	                        }
	                        Ext.Viewport.setMasked({
	                            xtype: 'loadmask',
	                            message: 'Conectando ...'
	                        });
	                        loginForm.submit({
	                            method: 'POST',
	                            url: host + '/login.aspx',
	                            success: function(form, action) {
	                                Ext.Viewport.setMasked(false);
	                                if (!action) { Ext.Msg.alert('Error', 'Verifique los parámetros de acceso'); }
	                                else {
	                                    if (action.success) {
	                                        limpiar();
	                                        var sto = Ext.getStore('statusStore');
	                                        sto.getProxy().clear();
	                                        sto.data.clear();
	                                        sto.sync();
	                                        var SAPUserStore = Ext.getStore('SAPUserStore');
	                                        var loUser = new SAPUserBE(action.user);
	                                        SAPUserStore.add(loUser);
	                                        SAPUserStore.sync();
	                                        listaOC.refresh();
	                                        listaOC.getStore().add(action.lstItemsResale);
	                                        listaOC.getStore().sync();
	                                        var now = new Date();
	                                        var dia = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
	                                        var mes = (now.getMonth() + 1) < 10 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
	                                        var minutos = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
	                                        listaOCPanel.items.items[2].setTitle('Actualizado  al ' + dia + '.' + mes + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + minutos);
	                                        panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'left' });
	                                    }
	                                    else {
	                                        Ext.Msg.alert('Error', action.errors.reason);
	                                    }
	                                }
	                            },
	                            failure: function(form, action) {
	                                Ext.Viewport.setMasked(false);
	                                if (!action.errors || !action.errors.reason)
	                                { Ext.Msg.alert('Error', 'Verifique los parámetros de acceso'); }
	                                else {
	                                    Ext.Msg.alert('Error', action.errors.reason);
	                                }
	                            }
	                        });
	                    }
	                    else {
	                        Ext.Msg.alert('Error', 'Verifique la conexión a internet');
	                    }
	                }
                }]
            }]
        });

        var introForm = new Ext.form.FormPanel({
            id: 'introForm',
            scrollable: 'vertical',
            centered: true,
            modal: true,
            items: [
            {
                xtype: 'component'
            },
            {
                xtype: 'button',
                text: 'Demo',
                ui: 'confirm',
                cls: 'intro',
                handler: function() {
                    var sto = Ext.getStore('statusStore');
                    var estado = Ext.ModelMgr.create({ valor: 'demo' }, 'statusModel');
                    sto.add(estado);
                    sto.sync();
                    listaOC.refresh();
                    var now = new Date();
                    var dia = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
                    var mes = (now.getMonth() + 1) < 10 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
                    var minutos = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
                    listaOCPanel.items.items[2].setTitle('Actualizado  al ' + dia + '.' + mes + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + minutos);
                    introForm.hide();
                    panelPrincipal.animateActiveItem(listaOCPanel, { type: 'fade', direction: 'left' });
                }
            },
            {
                xtype: 'component'
            },
            {
                xtype: 'button',
                text: 'Configuración',
                ui: 'confirm',
                cls: 'intro',
                handler: function() {
                    introForm.hide();
                    panelPrincipal.animateActiveItem(accesoForm, { type: 'fade', direction: 'left' });
                }
            },
            {
                xtype: 'component'
            }],
            listeners: {
                'painted': function(ele) {
                    var sto = Ext.getStore('accesoStore');
                    if (sto.last()) {
                        introForm.setModal(false);
                        introForm.hide();
                        ele.getParent().animateActiveItem(loginForm, { type: 'fade', direction: 'left' });
                    }
                    else {
                        var w = ele.getParent().element.getWidth();
                        var i1 = ele.items.items[0];
                        var i2 = ele.items.items[1];
                        var i3 = ele.items.items[2];
                        var i4 = ele.items.items[3];
                        var i5 = ele.items.items[4];
                        ele.setSize((w / 2.04), (w / 2.9));
                        i1.setSize((w / 2.2), (w / 20));
                        i2.setSize((w / 2.2), (w / 12));
                        i3.setSize((w / 2.2), (w / 18));
                        i4.setSize((w / 2.2), (w / 12));
                        i5.setSize((w / 2.2), (w / 20));
                    }
                }
            }
        });

        var panelPrincipal = new Ext.Panel({
            id: 'panelPrincipal',
            fullscreen: true,
            layout: 'card',
            cardAnimation: 'slide',
            items: [introForm, loginForm, accesoForm, listaOCPanel, detalleOC, itemOC, contactoOC, solicitanteOC]
        });

        Ext.Viewport.add(panelPrincipal);
    }
});